//
//  UIViewController+Category.swift
//  LXPageScrollVeiw
//
//  Created by 赵连勋 on 2019/4/11.
//  Copyright © 2019 赵连勋. All rights reserved.
//

import Foundation
import UIKit


public let LXViewControllerPropertyChangedNotification = "LXViewControllerPropertyChangedNotification"
private let LXInteractivePopKey  = "LXInteractivePopKey"
private let LXFullScreenPopKey   = "LXFullScreenPopKey"
private let LXPopMaxDistanceKey  = "LXPopMaxDistanceKey"
private let LXNavBarAlphaKey     = "LXNavBarAlphaKey"
private let LXStatusBarStyleKey  = "LXStatusBarStyleKey"
private let LXStatusBarHiddenKey = "LXStatusBarHiddenKey"
private let LXBackStyleKey       = "LXBackStyleKey"
private let LXPushDelegateKey    = "LXPushDelegateKey"
private let LXPopDelegateKey     = "LXPopDelegateKey"

@objc protocol LXViewControllerPushDelegate: NSObjectProtocol {
    @objc optional func pushToNextViewController()
}
@objc protocol LXViewControllerPopDelegate: NSObjectProtocol {
     @objc optional
    // 实现下面任意一个方法，滑动返回手势都会失效
    func viewControllerPopScrollBegan()
    func viewControllerPopScrollUpdate(progress: Double)
    func viewControllerPopScrollEnded()
}

extension UIViewController {
    //MARK:交换方法
    ///只调用一次
    public class func initializeMethod(){
        lx_swizzled_method(cls: self, originalSelector: #selector(UIViewController.viewWillAppear(_:)), swizzledSelector: #selector(UIViewController.lx_viewWillAppear))
        
    }
    @objc func lx_viewWillAppear(_ animated: Bool) {
        //在每次视图出现的时候重新设置当前控制器的手势
        postNotifi()
        self.lx_viewWillAppear(animated)
    }
    //MARK:添加属性
    /// 是否禁止当前控制器的滑动返回(包括全屏返回和边缘返回)
    var lx_interactivePopDisabled: Bool? {
        get {
            return objc_getAssociatedObject(self, LXInteractivePopKey) as? Bool
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXInteractivePopKey, lx_interactivePopDisabled, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            //当属行改变时，发送通知
            postNotifi()
        }
    }
    ///是否禁止当前控制器的全屏滑动返回
    var lx_fullScreenPopDisabled: Bool? {
        get {
            return objc_getAssociatedObject(self, LXFullScreenPopKey) as? Bool
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXFullScreenPopKey, lx_fullScreenPopDisabled, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            //当属行改变时，发送通知
            postNotifi()
        }
    }
    ///全屏滑动时，滑动区域距离屏幕左边的最大位置，默认是0：表示全屏都可滑动
    var lx_popMaxAllowedDistanceToLeftEdge: CGFloat? {
        get {
            return objc_getAssociatedObject(self, LXPopMaxDistanceKey) as? CGFloat
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXPopMaxDistanceKey, lx_popMaxAllowedDistanceToLeftEdge, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            //当属行改变时，发送通知
            postNotifi()
        }
    }
    ///设置导航栏的透明度
    var lx_navBarAlpha: CGFloat? {
        get {
            return objc_getAssociatedObject(self, LXNavBarAlphaKey) as? CGFloat
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXNavBarAlphaKey, lx_navBarAlpha, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            setNavBarAlpha(alpha: lx_navBarAlpha ?? 1)
        }
    }
    ///设置状态栏类型
    var lx_statusBarStyle: UIStatusBarStyle? {
        get {
             let style = objc_getAssociatedObject(self, LXStatusBarStyleKey)
            return (style != nil) ? style as? UIStatusBarStyle : UIStatusBarStyle.default
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXStatusBarStyleKey, lx_statusBarStyle, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            if self.responds(to: #selector(setNeedsStatusBarAppearanceUpdate)) {
                //调用隐藏方法
                _ = prefersStatusBarHidden()
                self.perform(#selector(setNeedsStatusBarAppearanceUpdate))
            }
        }
    }
    ///设置状态栏是否显示(default is NO 即不隐藏)
    var lx_statusBarHidden: Bool? {
        get {
            return objc_getAssociatedObject(self, LXStatusBarHiddenKey) as? Bool
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXStatusBarHiddenKey, lx_statusBarHidden, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            if self.responds(to: #selector(setNeedsStatusBarAppearanceUpdate)) {
                //调用隐藏方法
                _ = prefersStatusBarHidden()
                self.perform(#selector(setNeedsStatusBarAppearanceUpdate))
            }
        }
    }
    ///设置返回按钮的类型
    var lx_backStyle: LXNavigationBarBackStyle? {
        get {
            let style = objc_getAssociatedObject(self, LXBackStyleKey) as? LXNavigationBarBackStyle
            return (style != nil) ? style : LXNavigationBarBackStyle.black
        }
        set {
            //FIXME:作者此处为：OBJC_ASSOCIATION_RETAIN_NONATOMIC
            objc_setAssociatedObject(self, LXBackStyleKey, lx_backStyle, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
            if (self.navigationController?.children.count)! <= 1 {
                return
            }
            if self.lx_backStyle != LXNavigationBarBackStyle.none {
                //FIXME:此处需要设置一下自定义nav的返回按钮
//                let backImage = self.lx_backStyle == LXNavigationBarBackStyle.black ? UIImage(named: "btn_back_black") : UIImage(named: "btn_back_white")
                
            }
        }
    }
    ///push代理
    weak var lx_pushDelegate: LXViewControllerPushDelegate? {
        get {
            return objc_getAssociatedObject(self, LXPushDelegateKey) as? LXViewControllerPushDelegate
        }
        set {
            objc_setAssociatedObject(self, LXPushDelegateKey, lx_pushDelegate, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    ///pop代理，实现lx_popDelegate，原来的滑动返回手势将失效
    weak var lx_popDelegate: LXViewControllerPopDelegate? {
        get {
           return objc_getAssociatedObject(self, LXPopDelegateKey) as? LXViewControllerPopDelegate
        }
        set {
            objc_setAssociatedObject(self, LXPopDelegateKey, LXPopDelegateKey, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            // 当属性改变时，发送通知
            postNotifi()
        }
    }
    ///属性改变时发送通知
    func postNotifi() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: LXViewControllerPropertyChangedNotification), object: nil, userInfo: ["viewController": self])
    }
    func setNavBarAlpha(alpha: CGFloat) {
        var navBar: UINavigationBar?
        if self.isKind(of: LXNavigationBarViewController.self) {
            //FIXME:此处需要设置LXNavigationBarViewController，导航条的透明度
//            let vc = self as LXNavigationBarViewController
        } else {
            navBar = self.navigationController?.navigationBar
            let barBackgroundView = navBar?.subviews[0]
            let backgroundImageView = barBackgroundView?.subviews[0] as? UIImageView
            if navBar?.isTranslucent ?? false {
                if backgroundImageView != nil && backgroundImageView?.image != nil {
                    barBackgroundView?.alpha = alpha
                } else {
                    let backgroundEffectView = barBackgroundView?.subviews[1]
                    if backgroundEffectView != nil {
                        backgroundEffectView?.alpha = alpha
                    }
                }
            } else {
                barBackgroundView?.alpha = alpha
            }
        }
        //底部分割线
        navBar?.clipsToBounds = alpha == 0.0
    }
    //MARK:StatusBar
    func prefersStatusBarHidden() -> Bool {
        return self.lx_statusBarHidden ?? false
    }
    func preferredStatusBarStyle() -> UIStatusBarStyle {
        return self.lx_statusBarStyle ?? UIStatusBarStyle.default
    }
    //MARK: 当前显示的控制器
    func lx_visibleViewControllerIfExist() -> UIViewController? {
        if self.presentedViewController != nil {
            return self.presentedViewController!.lx_visibleViewControllerIfExist()
        }
        if self.isKind(of: UINavigationController.self) {
            return (self as! UINavigationController).topViewController!.lx_visibleViewControllerIfExist()
        }
        if self.isKind(of: UITabBarController.self) {
            return (self as! UITabBarController).selectedViewController!.lx_visibleViewControllerIfExist()
        }
        if self.isViewLoaded && self.view.window != nil {
            return self
        } else {
            print("找不到可见的控制器，viewcontroller.self = \(self), self.view.window = \(String(describing: self.view.window))")
            return nil
        }
    }
    ///返回按钮点击
    func backItemClick(sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
}
